package com.cxyzy.myapm

import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.app.Application
import android.content.Context
import android.os.Process

object ProcessUtils {
    @Volatile
    private var sProcessName: String? = null
    private val sNameLock = Any()
    fun myProcessName(context: Context): String? {
        if (sProcessName != null) {
            return sProcessName
        }
        synchronized(sNameLock) {
            if (sProcessName != null) {
                return sProcessName
            }
            sProcessName = obtainProcessName(context)
            return sProcessName
        }
    }

    private fun obtainProcessName(context: Context): String? {
        val pid = currentPid
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        var listTaskInfo: List<RunningAppProcessInfo?>? = null
        if (am != null) {
            listTaskInfo = am.runningAppProcesses
        }
        if (listTaskInfo != null && !listTaskInfo.isEmpty()) {
            for (info in listTaskInfo) {
                if (info != null && info.pid == pid) {
                    return info.processName
                }
            }
        }
        return null
    }

    /**
     * 获取当前应用进程的pid
     *
     * @return
     */
    val currentPid: Int
        get() = Process.myPid()

    val currentUid: Int
        get() = Process.myUid()

    /**
     * 是否主进程
     * 提供给外部使用
     * @param application
     * @return
     */
    fun isMainProcess(application: Application): Boolean {
        val pid = Process.myPid()
        var processName = ""
        val manager = application.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (process in manager.runningAppProcesses) {
            if (process.pid == pid) {
                processName = process.processName
            }
        }
        return application.packageName == processName
    }
}